import { NextRequest, NextResponse } from "next/server";
import { SqliteDatabase } from "@/lib/sqlite-database";

export async function GET(request: NextRequest) {
  try {
    const database = new SqliteDatabase();
    
    // 检查设备119-130的参数配置
    const deviceRange = [];
    for (let i = 119; i <= 130; i++) {
      deviceRange.push(i);
    }
    
    const deviceAnalysis = [];
    
    for (const deviceId of deviceRange) {
      const device = database.getDeviceById(deviceId);
      if (!device) {
        continue;
      }
      
      const namingParams = database.getNamingParametersByDeviceId(deviceId);
      const positionParams = database.getPositionParametersByDeviceId(deviceId);
      const baseParams = database.getBaseParametersByDeviceId(deviceId);
      
      deviceAnalysis.push({
        id: deviceId,
        device_id: device.device_id,
        name: device.name,
        specialty: device.specialty,
        classification_name: device.classification_name,
        position_table_id: device.position_table_id,
        parameterCounts: {
          naming: namingParams.length,
          position: positionParams.length,
          base: baseParams.length
        },
        shouldHavePosition: device.position_table_id && device.position_table_id !== "", // 根据位置表ID判断是否应该有位置参数
        actuallyHasPosition: positionParams.length > 0
      });
    }
    
    // 分析结果
    const analysis = {
      totalDevices: deviceAnalysis.length,
      devicesWithPositionTableId: deviceAnalysis.filter(d => d.shouldHavePosition).length,
      devicesWithPositionParams: deviceAnalysis.filter(d => d.actuallyHasPosition).length,
      inconsistentDevices: deviceAnalysis.filter(d => d.shouldHavePosition !== d.actuallyHasPosition),
      devicesToClean: deviceAnalysis.filter(d => !d.shouldHavePosition && d.actuallyHasPosition)
    };
    
    return NextResponse.json({
      success: true,
      message: "设备119-130参数验证完成",
      data: {
        deviceRange: "119-130",
        analysis,
        deviceDetails: deviceAnalysis,
        recommendations: [
          `共检查 ${analysis.totalDevices} 个设备`,
          `其中 ${analysis.devicesWithPositionTableId} 个设备有位置表ID配置`,
          `实际有 ${analysis.devicesWithPositionParams} 个设备有位置参数`,
          `发现 ${analysis.inconsistentDevices.length} 个设备配置不一致`,
          `需要清理 ${analysis.devicesToClean.length} 个设备的位置参数`
        ]
      }
    });
    
  } catch (error) {
    console.error("验证设备参数时出错:", error);
    return NextResponse.json(
      { 
        success: false, 
        message: "验证设备参数过程中发生错误",
        error: error instanceof Error ? error.message : "未知错误"
      },
      { status: 500 }
    );
  }
} 